﻿<div class="layui-fluid">
    <script src="/Scripts/src/lib/extend/exif.js"></script>
    <div class="layui-card">
        <script template type="text/html" lay-url="/Form/getKpiFormInfo" lay-data="{dataId:'{{layui.router().search.formId}}'}" lay-done="layui.data.done(d)">
            {{# if(d.data){ }}
            <h2 style="text-align:center;padding-top:10px">{{d.data.FormName}}</h2>
            <form class="layui-form re-quest-form" style="padding:20px" lay-filter="{{d.data.FormNo}}" id="{{d.data.FormNo}}">
                <input id="{{d.data.FormNo}}_photoimg" type="file" accept="image/*" capture="camera" style="display:none">
                <div class="layui-form-item">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-inline">
                        <input type="button" lay-submit lay-filter="{{d.data.FormNo}}-submit" value="提交" class="layui-btn layui-btn-default">
                    </div>
                </div>
            </form>
            {{# } }}
        </script>
    </div>
</div>

<script>

    layui.data.done = function (res) {
        if (res.data.tempForm) {
            var formItemsData = layui.admin.parse(res.data.tempForm);

            layui.use('reForm', function () {
                var $ = layui.$
                    , reForm = layui.reForm
                    , form = layui.form
                    , admin = layui.admin;

                var activeItem;
                $('#' + res.data.FormNo).on('click', '[photobtn]', function (event) {
                    activeItem = $(this).closest('[reitemid]');
                    $('#' + res.data.FormNo + '_photoimg').click();
                });
                $('#' + res.data.FormNo).on('click', '[removeimg]', function (event) {
                    var imgValue = $(this).closest('[reitemid]').find('input:hidden');
                    var imgUrl = $(this).parent().find('img').attr('src');
                    imgValue.val(imgValue.val().replace(';' + imgUrl, '').replace(imgUrl + ';', '').replace(imgUrl, ''));
                    $(this).parent().remove();
                });
                $('#' + res.data.FormNo + '_photoimg').change(function () {
                    var _file = this.files[0];
                    var Orientation = "";

                    var fileSize = Math.round(_file.size / 1024 / 1024);

                    EXIF.getData(_file, function () {
                        EXIF.getAllTags(this);
                        Orientation = EXIF.getTag(this, 'Orientation');
                    });

                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var img = new Image(), maxH = 300, maxW = 1080;

                        img.onload = function () {
                            var cvs = document.createElement('canvas'),
                                ctx = cvs.getContext('2d');

                            //if (img.height > maxH) {
                            //    img.width *= maxH / img.height;
                            //    img.height = maxH;
                            //}
                            if (img.width > maxW) {
                                img.height *= maxW / img.width;
                                img.width = maxW;
                            }
                            cvs.width = img.width;
                            cvs.height = img.height;

                            ctx.clearRect(0, 0, cvs.width, cvs.height);
                            ctx.drawImage(img, 0, 0, img.width, img.height);

                            var compressRate = reForm.getCompressRate(1, fileSize);

                            if (Orientation != "" && Orientation != 1 && Orientation != undefined) {
                                //alert('旋转处理' + Orientation);
                                var imgtmp = new Image();
                                imgtmp.src = cvs.toDataURL('image/jpeg', compressRate);
                                imgtmp.onload = function () {
                                    var cvstmp = document.createElement('canvas');
                                    switch (Orientation) {
                                        case 6://需要顺时针（向左）90度旋转
                                            //alert('需要顺时针（向左）90度旋转');
                                            reForm.rotateImg(this, 'left', cvstmp);
                                            break;
                                        case 8://需要逆时针（向右）90度旋转
                                            //alert('需要顺时针（向右）90度旋转');
                                            reForm.rotateImg(this, 'right', cvstmp);
                                            break;
                                        case 3://需要180度旋转
                                            //alert('需要180度旋转');
                                            reForm.rotateImg(this, 'right', cvstmp);//转两次
                                            reForm.rotateImg(this, 'right', cvstmp);
                                            break;
                                    }

                                    var dataUrl = cvstmp.toDataURL('image/jpeg', compressRate);
                                    uploadImg(dataUrl);
                                }
                                return;
                            }

                            var dataUrl = cvs.toDataURL('image/jpeg', compressRate);
                            uploadImg(dataUrl);
                        };
                        img.src = e.target.result;
                        //img.src = this.result;
                    };
                    reader.readAsDataURL(_file);
                });
                function uploadImg(dataUrl) {
                    var imgArea = activeItem.find('.imgArea');
                    var imgValue = activeItem.find('input:hidden');
                    admin.req({
                        api: layui.setter.fileApi,
                        url: "/Files/UploadWxPic",
                        type: 'post',
                        loading: true,
                        data: { localData: dataUrl, source: 'mobileFormPhoto' },
                        done: function (res) {
                            imgArea.append('<li><img src="' + layui.setter.fileApi + res.result + '"/><span removeimg>删除</span></li>');
                            if (imgValue.val() === '')
                                imgValue.val(res.result);
                            else
                                imgValue.val(imgValue.val() + ';' + res.result);
                        }
                    })
                }

                var html = admin.getFormHtml(formItemsData);

                $('[lay-filter="' + res.data.FormNo + '"]').prepend(html);

                $.each(formItemsData, function (idx, json) {
                    reForm.bindFormHtml(json, res.param, res.data.FormNo);
                });

                form.verify(reForm.verify);
                $('[lay-filter="' + res.data.FormNo + '"] [lay-verType]').removeAttr("lay-verType");
                form.render(null, res.data.FormNo);
                form.on('submit(' + res.data.FormNo + '-submit)', function (data) {
                    var formData = reForm.getFilterFormData(data, res.data.FormNo);
                    admin.req({
                        url: '/Tool/saveFormData',
                        type: 'post',
                        loading: true,
                        data: $.extend(formData, { _FormID: res.data.FormID }),
                        done: function (newRes) {

                            if (newRes.data && newRes.data.tempForm) {
                                formItemsData = layui.admin.parse(newRes.data.tempForm);

                                html = admin.getFormHtml(formItemsData);
                                var newForm = '<form class="layui-form re-quest-form"  style="padding:20px" lay-filter="' + newRes.data.FormNo + '">'
                                    + html + '<div class="layui-form-item">'
                                    + '<label class="layui-form-label"></label>'
                                    + '<div class="layui-input-inline">'
                                    + '<input type="button" lay-submit lay-filter="' + newRes.data.FormNo + '-submit" value="提交" class="layui-btn layui-btn-default">'
                                    + '</div>'
                                    + '</div>'
                                    + '</form>';

                                $('[lay-filter="' + res.data.FormNo + '"]').after(newForm);

                                $.each(formItemsData, function (idx, json) {
                                    reForm.bindFormHtml(json, null, newRes.data.FormNo);
                                });
                                form.verify(reForm.verify);
                                form.render(null, newRes.data.FormNo);

                                $('[lay-filter="' + res.data.FormNo + '"] [name="ID"]').val(newRes.data.RID);
                                $('[lay-filter="' + res.data.FormNo + '"] [name="No"]').val(newRes.data.RNo);

                                $('[lay-filter="' + newRes.data.FormNo + '"] [name="RNo"]').val(newRes.data.RNo);
                                $('[lay-filter="' + newRes.data.FormNo + '"] [name="_RFormID"]').val(res.data.FormID);

                                //$('[lay-filter="' + res.data.FormNo + '-submit"]').prop('disabled', true);
                                $('[lay-filter="' + res.data.FormNo + '"]').children(".layui-form-item:last-child").hide();

                                form.on('submit(' + newRes.data.FormNo + '-submit)', function (data) {

                                    $('[lay-filter="' + res.data.FormNo + '-submit"]').click();

                                    formData = reForm.getFilterFormData(data, newRes.data.FormNo);

                                    admin.req({
                                        url: '/Tool/saveFormData',
                                        type: 'post',
                                        loading: true,
                                        data: $.extend(formData, { _FormID: newRes.data.FormID }),
                                        done: function () {
                                            window.location.reload();
                                        }
                                    })

                                    return false;
                                })
                            }
                            else
                                window.location.reload();
                        }
                    })
                    return false;
                });
            })
        }
    }
</script>
